package com.ukao.pad.ui;


import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.ukao.pad.R;
import com.ukao.pad.base.MvpFragment;
import com.ukao.pad.bean.AccountLoginBean;
import com.ukao.pad.consts.SaveParamets;
import com.ukao.pad.dialog.AccountDialogFragment;
import com.ukao.pad.eventbus.MembershipCardEvent;
import com.ukao.pad.listener.OnConfirmClickListener;
import com.ukao.pad.presenter.LoginPesenter;
import com.ukao.pad.rfid.MembershipCardHelper;
import com.ukao.pad.utils.CheckUtils;
import com.ukao.pad.utils.L;
import com.ukao.pad.utils.T;
import com.ukao.pad.utils.Utils;
import com.ukao.pad.view.loginView;
import com.ukao.pad.widget.StateButton;
import com.ukao.pad.widget.ZProgressHUD;

import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;




/**
 * 刷卡登录
 */
public class SwipingCardFragment extends MvpFragment<LoginPesenter> implements loginView {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.log_in)
    TextView logIn;
    Unbinder unbinder;
    @BindView(R.id.account_btn)
    StateButton accountBtn;


    private String mParam1;
    private String mParam2;
    private Handler mHandler = new Handler();
    private String rfidSecretCard;
    private ZProgressHUD progressDialog;
    private boolean isVisible;
    private AccountDialogFragment mAccountDialog;
    private  boolean isNfcReadCard=false;


    public static SwipingCardFragment newInstance(String param1, String param2) {
        SwipingCardFragment fragment = new SwipingCardFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    protected LoginPesenter createPresenter() {
        return new LoginPesenter(this);
    }

    @Override
    protected void initView() {


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_swiping_cardragment, container, false);
        unbinder = ButterKnife.bind(this, view);
        isNfcReadCard=true;
        initView();
        return view;
    }


    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        isVisible = false;
        mHandler.removeCallbacksAndMessages(null);

    }


    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        isVisible = true;
        isNfcReadCard=true;
        postDelayedReadCard();


    }


    @Override
    protected boolean useEventBus() {
        return true;
    }




    @Subscribe
    public void onEvent(MembershipCardEvent event) {
        switch (event.getMessage()) {
            case add:/*成功*/
                rfidSecretCard = (String) event.getData();
                mvpPresenter.appSecretData();

                break;
            case fali:/*读卡失败*/

                String error = (String) event.getData();
                T.show(error);
                postDelayedReadCard();
                break;
            case notFound:/*没有卡*/

                postDelayedReadCard();

                break;

            case   nfc_read:  /*商米NFC读卡*/
                if (!isNfcReadCard)return;
                rfidSecretCard=(String)event.getData();
                mvpPresenter.appSecretData();
                break;
        }
    }


    /**
     * 读卡
     */
    private void postDelayedReadCard() {
        if (!isVisible) return;
        if (mAccountDialog!=null&&mAccountDialog.getDialog()!=null&&mAccountDialog.getDialog().isShowing())return;
        mHandler.removeCallbacksAndMessages(null);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                L.i("读卡");
              MembershipCardHelper.getInstance().readUserId();


            }
        }, 2500);

    }





    @Override
    public void loadloginSucceed(AccountLoginBean mitem) {

        AccountLoginBean.FactoryInfoBean storeInfo = mitem.getFactoryInfo();
        /*工厂信息*/
        if (!CheckUtils.isNull(storeInfo)) {
            SaveParamets.setStoreName(storeInfo.getName());
            SaveParamets.setCreateTimep(storeInfo.getCreateTime() + "");
            SaveParamets.setRegionalDesc(storeInfo.getRegionalDesc());
            SaveParamets.setAddrDesc(storeInfo.getAddrDesc());
            // SaveParamets.setOrderEnter(storeInfo.getInType());


        }

        SaveParamets.setAutoPutaway(mitem.getShelfMode());
        SaveParamets.setMercInfo(mitem.getMercInfo().getName());
        SaveParamets.saveToken(_mActivity, mitem.getAccessToken());
        SaveParamets.saveUseName(_mActivity, mitem.getWorkerInfo().getName());
        SaveParamets.saveUsePhone(_mActivity, mitem.getWorkerInfo().getPhone());
        SaveParamets.saveHeadimgPath(_mActivity, mitem.getWorkerInfo().getImgPath());
        SaveParamets.setIsLogin( true);
        isNfcReadCard=false;
        Intent mIntent = new Intent(_mActivity, MainActivity.class);
        startActivity(mIntent);
        getActivity().finish();

    }

    @Override
    public void loadFailure(String message) {
        if (!CheckUtils.isEmpty(message)){
            T.show(message);
        }

        postDelayedReadCard();


    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);

        postDelayedReadCard();
    }

    @Override
    public void appSecretSucceed(String appSecret) {

        SaveParamets.saveloginSign(Utils.getContext(), appSecret);
        mvpPresenter.swipingCardlogin(rfidSecretCard);


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        MembershipCardHelper.getInstance().onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }



    @Override
    public void onNoNewWork() {

    }

    @OnClick({R.id.account_btn, R.id.log_in})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.account_btn:
                mHandler.removeCallbacksAndMessages(null);
                mAccountDialog=AccountDialogFragment.newInstance("","");
                mAccountDialog.setOnConfirmClickListener(mOnConfirmClickListener);
                mAccountDialog.show(getChildFragmentManager(),mAccountDialog.getClass().getName());
                break;
            case R.id.log_in:

                break;
        }
    }


    private OnConfirmClickListener mOnConfirmClickListener=new OnConfirmClickListener() {
        @Override
        public void onChildItemClick(int id, Object msg) {
            switch (id) {
                case AccountDialogFragment.LOGIN_SUCCEED:
                    if (!CheckUtils.isNull(mAccountDialog)){ mAccountDialog.dismiss(); }
                    if (!CheckUtils.isNull(msg)){
                        AccountLoginBean mitem = (AccountLoginBean) msg;
                        loadloginSucceed(mitem);
                    }
                    break;
                case AccountDialogFragment.LOGIN_DIALOG_DESTORT:
                    postDelayedReadCard();
                    break;

            }


        }
    };

}
